package com.project.demo.controller;

import com.project.demo.entity.UserSeatArrangement;
import com.project.demo.entity.User;
import com.project.demo.service.UserSeatArrangementService;
import com.project.demo.service.SmsService;
import com.project.demo.service.UserService;
import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户排座：(UserSeatArrangement)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("/user_seat_arrangement")
public class UserSeatArrangementController extends BaseController<UserSeatArrangement, UserSeatArrangementService> {

    /**
     * 用户排座对象
     */
    @Autowired
    public UserSeatArrangementController(UserSeatArrangementService service) {
        setService(service);
    }

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    @Autowired
    private com.project.demo.service.MessageNotificationService messageNotificationService;


    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        Map<String,Object> paramMap = service.readBody(request.getReader());
        this.addMap(paramMap);
        
        // 自动创建消息通知
        try {
            Integer seatArrangementId = null;
            Integer userId = null;
            
            // 从参数中获取用户ID
            if (paramMap.get("participants") != null) {
                userId = Integer.parseInt(paramMap.get("participants").toString());
            }
            
            // 从参数中获取主键ID（如果存在，说明是更新操作；如果不存在，需要查询刚插入的记录）
            if (paramMap.get("user_seat_arrangement_id") != null) {
                seatArrangementId = Integer.parseInt(paramMap.get("user_seat_arrangement_id").toString());
            } else {
                // 如果是新增操作，需要查询刚插入的记录ID
                // 使用更精确的查询条件：participants + 其他关键字段的组合
                Map<String, String> query = new HashMap<>();
                if (userId != null) {
                    query.put("participants", userId.toString());
                }
                // 添加其他唯一字段来确保查询到正确的记录
                if (paramMap.get("conference_name") != null) {
                    query.put("conference_name", paramMap.get("conference_name").toString());
                }
                if (paramMap.get("seat_number") != null) {
                    query.put("seat_number", paramMap.get("seat_number").toString());
                }
                Map<String, String> config = new HashMap<>();
                config.put("order", "create_time desc");
                config.put("size", "1");
                Query select = service.select(query, config);
                Object resultObj = select != null && select.getResultList().size() > 0 ? select.getResultList().get(0) : null;
                
                if (resultObj instanceof UserSeatArrangement) {
                    UserSeatArrangement seatArrangement = (UserSeatArrangement) resultObj;
                    seatArrangementId = seatArrangement.getUser_seat_arrangement_id();
                }
            }
            
            // 如果找到了记录ID，创建消息通知
            // 优先使用 paramMap 中的值（这些是前端提交的实际数据）
            if (seatArrangementId != null && userId != null) {
                String conferenceName = paramMap.get("conference_name") != null ? paramMap.get("conference_name").toString() : null;
                String seatNumber = paramMap.get("seat_number") != null ? paramMap.get("seat_number").toString() : null;
                String meetingVenue = paramMap.get("meeting_venue") != null ? paramMap.get("meeting_venue").toString() : null;
                String userName = paramMap.get("user_name") != null ? paramMap.get("user_name").toString() : null;
                
                messageNotificationService.createSeatMessage(
                    userId,
                    seatArrangementId,
                    conferenceName,
                    seatNumber,
                    meetingVenue,
                    userName
                );
            }
        } catch (Exception e) {
            log.error("创建排座消息通知失败", e);
        }
        
        return success(1);
    }

    /**
     * 发送排座通知短信
     */
    @PostMapping("/send_sms")
    public Map<String, Object> sendSms(HttpServletRequest request) {
        try {
            // 先尝试从请求体读取（POST数据）
            Map<String, Object> bodyMap = null;
            try {
                bodyMap = service.readBody(request.getReader());
            } catch (Exception e) {
                log.debug("读取请求体失败，尝试从查询参数读取: {}", e.getMessage());
            }
            
            // 从请求体或查询参数中获取 user_seat_arrangement_id
            String userSeatArrangementId = null;
            if (bodyMap != null && bodyMap.get("user_seat_arrangement_id") != null) {
                userSeatArrangementId = bodyMap.get("user_seat_arrangement_id").toString();
            } else {
                Map<String, String> query = service.readQuery(request);
                userSeatArrangementId = query.get("user_seat_arrangement_id");
            }
            
            if (userSeatArrangementId == null || userSeatArrangementId.isEmpty()) {
                return error(400, "user_seat_arrangement_id 不能为空");
            }

            // 查询排座信息
            Map<String, String> seatQuery = new HashMap<>();
            seatQuery.put("user_seat_arrangement_id", userSeatArrangementId);
            Map<String, String> seatConfig = new HashMap<>(); // 传递空配置而不是 null
            Query seatQueryResult = service.select(seatQuery, seatConfig);
            Object seatObj = seatQueryResult != null ? seatQueryResult.getSingleResult() : null;
            
            if (seatObj == null) {
                return error(404, "未找到排座信息");
            }

            UserSeatArrangement seatArrangement;
            if (seatObj instanceof UserSeatArrangement) {
                seatArrangement = (UserSeatArrangement) seatObj;
            } else {
                return error(500, "数据格式错误");
            }

            // 获取用户手机号
            String phoneNumber = null;
            if (seatArrangement.getParticipants() != null) {
                Map<String, String> userQuery = new HashMap<>();
                userQuery.put("user_id", seatArrangement.getParticipants().toString());
                Query userQueryResult = userService.select(userQuery, null);
                Object userObj = userQueryResult != null ? userQueryResult.getSingleResult() : null;
                if (userObj instanceof User) {
                    User user = (User) userObj;
                    phoneNumber = user.getPhone();
                }
            }

            if (phoneNumber == null || phoneNumber.isEmpty()) {
                return error(400, "用户手机号为空，无法发送短信");
            }

            // 构建短信内容
            Map<String, String> smsParams = new HashMap<>();
            smsParams.put("conference_name", seatArrangement.getConference_name() != null ? seatArrangement.getConference_name() : "");
            smsParams.put("seat_number", seatArrangement.getSeat_number() != null ? seatArrangement.getSeat_number() : "");
            smsParams.put("meeting_venue", seatArrangement.getMeeting_venue() != null ? seatArrangement.getMeeting_venue() : "");
            smsParams.put("user_name", seatArrangement.getUser_name() != null ? seatArrangement.getUser_name() : "");

            // 发送短信
            Map<String, Object> smsResult = smsService.sendSms(phoneNumber, null, smsParams);
            String smsContent = smsService.buildNotificationContent("排座", smsParams);
            smsResult.put("content", smsContent);

            log.info("发送排座通知短信 - 手机号: {}, 内容: {}", phoneNumber, smsContent);

            return success(smsResult);
        } catch (Exception e) {
            log.error("发送排座通知短信失败", e);
            return error(500, "发送短信失败: " + e.getMessage());
        }
    }

}
